package com.jackeysun.util

import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Rect

/**
 *   Created by sunxunchao on 2021/11/19.
 */


infix fun Bitmap.scale(ratio: Float): Bitmap {
    val width = this.width
    val height = this.height
    val matrix = Matrix()
    matrix.setScale(ratio, ratio)
    val newBitmap = Bitmap.createBitmap(this, 0, 0, width, height, matrix, false)
    if (newBitmap.equals(this)) {
        return newBitmap
    }
    this.recycle()
    return newBitmap
}

infix fun Bitmap.rotate(degrees: Float): Bitmap {
    val width = this.width
    val height = this.height
    val matrix = Matrix()
    matrix.setRotate(degrees)
    val newBitmap = Bitmap.createBitmap(this, 0, 0, width, height, matrix, false)
    if (newBitmap.equals(this)) {
        return newBitmap
    }
    this.recycle()
    return newBitmap
}

infix fun Bitmap.crop(rect: Rect): Bitmap {
    val w = rect.right - rect.left
    val h = rect.bottom - rect.top
    return Bitmap.createBitmap(this, 0, 0, w, h, null, false)
}

infix fun Bitmap.translateX(dx: Float): Bitmap {
    val width = this.width
    val height = this.height
    val matrix = Matrix()
    matrix.setTranslate(dx, 0f)
    val newBitmap = Bitmap.createBitmap(this, 0, 0, width, height, matrix, false)
    if (newBitmap.equals(this)) {
        return newBitmap
    }
    this.recycle()
    return newBitmap
}

infix fun Bitmap.translateY(dy: Float): Bitmap {
    val width = this.width
    val height = this.height
    val matrix = Matrix()
    matrix.setTranslate(0f, dy)
    val newBitmap = Bitmap.createBitmap(this, 0, 0, width, height, matrix, false)
    if (newBitmap.equals(this)) {
        return newBitmap
    }
    this.recycle()
    return newBitmap
}

fun Bitmap.combination(block: Matrix.() -> Unit): Bitmap {
    val width = this.width
    val height = this.height
    val matrix = Matrix()
    block(matrix)
    val newBitmap = Bitmap.createBitmap(this, 0, 0, width, height, matrix, false)
    if (newBitmap.equals(this)) {
        return newBitmap
    }
    this.recycle()
    return newBitmap
}

